#include "Sphere.h"

namespace Geometry
{
	bool Sphere::intersect(const Ray& _r, Point& _p, float& _t)
	{
		Point& O = c();
		Point& P = _r.p();
		Vector& V = _r.q();

		Vector& W = ( ( ( ( O - P ) * V ) * V ) / ( V * V ) ) + P - O;

		float mag_W_sqr = W.mag() * W.mag();
		float r_sqr = r() * r();
		float alpha = sqrt( r_sqr - mag_W_sqr );

		//no intersections
		if( mag_W_sqr > r_sqr )
		{
			return false;
		}
		// 1 intersection
		else if( mag_W_sqr == r_sqr )
		{
			_t = ( ( ( O - P ) * V ) / ( V * V ) );

			if( _t > 0 )
			{
				_p = P + _t * V;  
				return true;
			}
			else
			{
				return false;
			}
		}
		//2 intersections
		else
		{
			float t = ( ( ( O - P ) * V ) / ( V * V )  - (alpha / V.mag() ) );

			if( t > -0.01 )
			{
				_t = t;
				_p = P + _t * V;
				return true;
			}
			else
			{
				return false;
			}
		}

	}
}

